using UnityEngine;
using System.Collections;

public class ShopGui : MonoBehaviour, IClickableGui {
	/**
	 * Rectangle representing the current window appearance
	 */
	const int SHOP_NUM_ROWS = 3;
	const int SHOP_NUM_COLS = 6;
	const int CART_NUM_ROWS = 1;
	const int CART_NUM_COLS = 6;
	static bool DEBUG = true;
	
	private Rect WindowRect;
	public string title = "Shop";
	
	private int WindowID = 1;
	
	/* boxes representing shop's inventory */
	ItemContainerGui inv_boxes = null;
	
	/* boxes representing shopping cart */
	ItemContainerGui cart_boxes = null;
	
	bool destroy_self = false;
	
	Rect close_rect;
	
	void Awake () {
		this.inv_boxes = new ItemContainerGui(new Vector2(0, 0),
			ShopGui.SHOP_NUM_ROWS, ShopGui.SHOP_NUM_COLS);
		this.cart_boxes = new ItemContainerGui(new Vector2(0, this.inv_boxes.height),
			ShopGui.CART_NUM_ROWS, ShopGui.CART_NUM_COLS);
	}
	
	void Start () {
		/* inventory is on top of cart, so only add heights */
		this.WindowRect = new Rect(30,30,
			this.inv_boxes.width,
			this.inv_boxes.height + this.cart_boxes.height);
	}
	
	void OnGUI () {
		this.WindowRect = GUI.Window (this.WindowID, this.WindowRect, WindowFunc, this.title);
		if (this.destroy_self) {
			Destroy (this);
		}
	}
	
	void WindowFunc(int id) {
		
		if (this.destroy_self) {
			return;
		}
		
		/* Draw shop inventory */
		for (int row=0; row<this.inv_boxes.num_rows; row++) {
			for (int col=0; col<this.inv_boxes.num_columns; col++) {
				GUI.Box (this.inv_boxes.GetBoxRect (row, col), (string)null);
			}
		}
		
		/* Draw shopping cart */
		for (int row=0; row<this.cart_boxes.num_rows; row++) {
			for (int col=0; col<this.cart_boxes.num_columns; col++) {
				GUI.Box (this.cart_boxes.GetBoxRect (row, col), (string)null);
			}
		}
		
		this.close_rect = new Rect(
			this.inv_boxes.width - this.inv_boxes.top_border, 0,
			this.inv_boxes.top_border, this.inv_boxes.top_border);
		GUI.Box (this.close_rect, "x");
		
		GuiIO.HandleMouseClick(this, Event.current);
		
	}
	
	public void RightClick(Event e) {
		Vector2 gui_pos;
		string prefix = "";
		bool found;
		Pair<int, int> row_and_col = new Pair<int, int>(0, 0);
			
		gui_pos = e.mousePosition;
		
		found = false;
		if (this.inv_boxes.GetBoxFromPos (gui_pos,out row_and_col)) {
			prefix = "inv";
			found = true;
		} else if (this.cart_boxes.GetBoxFromPos(gui_pos, out row_and_col)) {
			prefix = "cart";
			found = true;
		}
		
		switch (e.type) {
		case EventType.MouseDown:
			if (found) {
				if (ShopGui.DEBUG) {
					Debug.Log (prefix +
						"clicked row " + row_and_col.Item1.ToString () +
						" col " + row_and_col.Item2.ToString ());
				}
			}
			break;
		case EventType.MouseUp:
			break;
		default:
			/* should be unreachable */
			break;
		}
	}
	
	public void LeftClick(Event e) {
		if ((e.type == EventType.MouseUp) && (this.close_rect.Contains (e.mousePosition))) {
			this.destroy_self = true;
		}
	}
}
